package com.evan.common.utils;

import com.evan.common.bit.CommandConstEnum;
import com.evan.common.pojo.ZkServerInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SocketClient {

    private String host;
    private int port;
    private Socket socket;

    public SocketClient(String host, int port) throws IOException {
        this.host = host;
        this.port = port;
        socket = new Socket(host,port);
    }

    public void closeSocket() throws IOException {
        socket.close();
    }

    public List<String> sendCommand(CommandConstEnum command) throws IOException {
        if (command == null){
            return null;
        }
        List<String> result = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try{

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(command.getVal().getBytes());
            outputStream.flush();
            socket.shutdownOutput();
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while((line = reader.readLine()) != null){
                buffer.append(line);
                buffer.append("");
            }
            result.add(buffer.toString());

        } catch (IOException e) {
            e.printStackTrace();
            this.closeSocket();
        }finally {
            if(reader != null){
                reader.close();
            }
            socket.close();
        }
        return result;
    }

    public String sendStat() throws IOException {
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = null;
        try{

            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("stat".getBytes());
            outputStream.flush();
            socket.shutdownOutput();
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line;
            while((line = reader.readLine()) != null){
                if(line.indexOf("Mode: ") != -1){
                    buffer.append(line.replaceAll("Mode: ",""));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
            this.closeSocket();
        }finally {
            if(reader != null){
                reader.close();
            }
            socket.close();
        }
        return buffer.toString();
    }

    public void connect(ZkServerInfo zkServer,int timeout) throws IOException {
        InetSocketAddress endpoint = new InetSocketAddress(zkServer.getIp(), zkServer.getPort());
        socket.connect(endpoint,timeout);
    }
}
